# app/grade_mgmt.py

from flask import Blueprint, request, jsonify, session, abort
from functools import wraps
from . import db
from .models import Grade  # 下面会在 models.py 中添加 Grade

bp = Blueprint('grade_mgmt', __name__, url_prefix='/api/grades')

def login_required(f):
    @wraps(f)
    def w(*args, **kwargs):
        uid = session.get('user_id')
        if not uid:
            abort(401)
        return f(*args, **kwargs)
    return w

@bp.before_request
@login_required
def ensure_login():
    pass

@bp.route('', methods=['GET'])
def list_grades():
    uid = session['user_id']
    items = Grade.query.filter_by(owner_id=uid).order_by(Grade.seq).all()
    return jsonify([{"id":g.id, "name":g.name} for g in items]), 200

@bp.route('', methods=['POST'])
def create_grade():
    uid = session['user_id']
    data = request.get_json() or {}
    name = data.get('name','').strip()
    if not name:
        return jsonify({"error":"年级名必填"}),400
    max_seq = db.session.query(db.func.max(Grade.seq)).filter_by(owner_id=uid).scalar() or 0
    g = Grade(name=name, owner_id=uid, seq=max_seq+1)
    db.session.add(g); db.session.commit()
    return jsonify({"id":g.id,"name":g.name}),201

@bp.route('/<int:gid>', methods=['PUT'])
def update_grade(gid):
    uid = session['user_id']
    g = Grade.query.filter_by(id=gid, owner_id=uid).first_or_404()
    data = request.get_json() or {}
    name = data.get('name','').strip()
    if not name:
        return jsonify({"error":"年级名必填"}),400
    g.name = name
    db.session.commit()
    return jsonify({"message":"更新成功"}),200

@bp.route('/<int:gid>', methods=['DELETE'])
def delete_grade(gid):
    uid = session['user_id']
    g = Grade.query.filter_by(id=gid, owner_id=uid).first_or_404()
    db.session.delete(g); db.session.commit()
    # 重排 seq
    items = Grade.query.filter_by(owner_id=uid).order_by(Grade.seq).all()
    for idx,gr in enumerate(items,1):
        gr.seq = idx
    db.session.commit()
    return jsonify({"message":"删除成功"}),200

@bp.route('/<int:gid>/move', methods=['POST'])
def move_grade(gid):
    uid = session['user_id']
    g = Grade.query.filter_by(id=gid, owner_id=uid).first_or_404()
    dir = (request.get_json() or {}).get('dir')
    if dir=='up':
        other = Grade.query.filter(Grade.owner_id==uid, Grade.seq<g.seq).order_by(Grade.seq.desc()).first()
    else:
        other = Grade.query.filter(Grade.owner_id==uid, Grade.seq>g.seq).order_by(Grade.seq.asc()).first()
    if other:
        g.seq, other.seq = other.seq, g.seq
        db.session.commit()
    return jsonify({"message":"移动成功"}),200
